Intro to Svelte action
Posted on 2023-04-01 by
henrikvilhelmberglundActions are lifecycle functions for your elements . They are called whenever the element is mounted to the DOM.
You add them by adding use:functionName in the element.
They can also contain an optional destroy() function that is called whenever the element is removed from the DOM.
You can pass two parameters, node and params . Node is the element itself and params are whatever you pass into the action using the use:action={} syntax.
In this example I'm passing params for the h1 and changing its text.
Hello
My text will change soon!
<script>
let show = true;
function action(node, params) {
let myTimeout;
console.log("hi! I was created!", node);
if (params) {
myTimeout = setTimeout(() => {
node.innerHTML = params;
console.log("wow! I was changed!");
}, 3000);
}
return {
destroy() {
console.log("bye! I was destroyed");
if (params) {
clearTimeout(myTimeout);
}
},
};
}
</script>
<input type="checkbox" bind:checked={show} />
{#if show}
<div use:action>Hello</div>
<h1 use:action={"My text changed! 😊"}>My text will change soon!</h1>
{/if}
<style>
</style>